package com.wys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wys.dao.CategoryDao;
import com.wys.exception.CustomerException;
import com.wys.pojo.Category;
import com.wys.pojo.Dish;
import com.wys.pojo.Setmeal;
import com.wys.result.R;
import com.wys.service.CategoryService;
import com.wys.service.DishService;
import com.wys.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements CategoryService {

    /**
     *  新增分类
     * @param category
     * @return
     */
    @Override
    public R<String> addCategory(Category category) {
        save(category);
        return R.success("分类添加成功！");
    }

    /**
     *  分页查询
     * @param page 当前页
     * @param pageSize  页面大小
     * @return
     */
    @Override
    public R<Page> getPage(int page, int pageSize) {
        //分页构造器
        Page getPage = new Page(page,pageSize);
        //分页查询条件构造器
        LambdaQueryWrapper<Category> wrapper=new LambdaQueryWrapper<>();
        //按排序字段排序
        wrapper.orderByAsc(Category::getSort);
        //分页查询
        page(getPage,wrapper);
        return R.success(getPage);
    }

    /**
     *  删除分类
     * @param id 要删除的分类ID
     * @return
     */
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;
    @Override
    public boolean deleted(Long id) {
        //查询要删除的菜品分类是否关联菜品
        LambdaQueryWrapper<Dish> wrapper1=new LambdaQueryWrapper<>();
        wrapper1.eq(Dish::getCategoryId,id);
        int count1 = dishService.count(wrapper1);
        //关联相关菜品则抛出一个业务异常
        if(count1 > 0){
            //抛出一个业务异常
            throw new CustomerException("当前分类已关联菜品,禁止删除！");
        }

        //查询要删除的套餐分类是否关联套餐
        LambdaQueryWrapper<Setmeal> wrapper2 = new LambdaQueryWrapper();
        wrapper2.eq(Setmeal::getCategoryId,id);
        int count2 = setmealService.count(wrapper2);
        //关联相关套餐则抛出一个业务异常
        if(count2 > 0){
            //抛出一个业务异常
            throw new CustomerException("当前分类已关联套餐,禁止删除！");
        }

        //不关联，可以直接删除
        return removeById(id);
    }

    /**
     *  根据分类查询，来在添加菜品页面进行展示
     * @param category
     * @return
     */
    @Override
    public R<List<Category>> findCategoryByType(Category category) {
        LambdaQueryWrapper<Category> wrapper=new LambdaQueryWrapper();
        wrapper.eq(category.getType() != null,Category::getType,category.getType());
        wrapper.orderByAsc(Category::getSort);
        List<Category> categoryList = list(wrapper);
        return R.success(categoryList);
    }
}
